let layer;
let form;
let element;
let video;//视频流对象
let context;//绘制对象
let canvas;//画布对象
let flag = false;
// 视频投影循环
let videoInterval;
// 登录请求循环
let faceLoginInterval;
// 登录超时定时器
let loginTimeOut;
let loginUser;
$(function () {
    layui.use(['layer', 'form', 'element'], function () {
        layer = layui.layer;
        form = layui.form;
        element = layui.element;
        // 选项卡切换监听
        element.on('tab(loginTab)', function (data) {
            switch (data.index) {
                case 0:
                    closeCamera()
                    break;
                case 1:
                    closeCamera()
                    break;
                case 2:
                    openCamera();
                    break;
                default:
                    break;
            }
        });
        // 快速登录表单提交监听
        form.on('submit(fastLoginFormSubmit)', function (data) {
            validateCodeLogin(data.field);
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });
        // 密码登录表单提交监听
        form.on('submit(pswLoginFormSubmit)', function (data) {
            pswLogin(data.field);
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });
    });
})

function pswLogin(data) {
    $.ajax({
        async: true,
        type: "POST",
        url: "/user/pswLogin",
        data: data,
        success: function (result) {
            loginSuccess(result, data);
        }, error: function () {
            layer.msg('出错了');
        }
    });
}

function loginSuccess(result, data) {
    if (result !== undefined) {
        if (data.autoLogin === 'on') {
            let obj = {};
            obj.userPhone = result.userPhone;
            obj.md5 = result.userPsw;
            localStorage.setItem('autoLogin', JSON.stringify(obj));
        } else {
            localStorage.removeItem('autoLogin');
        }
        layer.msg('登录成功');
        setTimeout(function () {
            window.location.reload();
        }, 1000)
    } else {
        layer.msg('登录失败');
    }
}

// 登出
function logout() {
    layer.open({
        title: false,
        closeBtn: false,
        content: '<div class="container"><h5 class="text-center">确认退出？</h5></div>',
        skin: 'confirm-skin',
        btnAlign: 'c',
        move: false,
        btn: ['是', '否'],
        yes: function (index, layero) {
            console.log(window.location.pathname)
            $.ajax({
                async: false,
                type: "POST",
                url: "/user/logOut",
                success: function (data) {
                    if (data) {
                        layer.msg("登出成功");
                        localStorage.removeItem('autoLogin');
                    } else {
                        layer.msg("登出失败");
                    }
                    setTimeout(function () {
                        if (window.location.pathname === '/front/userGallery.jsp') {
                            window.location.href = '/index.jsp';
                        } else {
                            window.location.reload();
                        }
                    }, 1000 * 1)
                }
            });
        },
        btn2: function (index, layero) {
        }
    });


}

// 关闭摄像头
function closeCamera() {
    //判断摄像头是否打开
    if (flag) {
        //关闭摄像头
        video.srcObject.getTracks()[0].stop();
        flag = false;
        clearInterval(videoInterval);
        clearInterval(faceLoginInterval);
        clearTimeout(loginTimeOut);
        context.clearRect(0, 0, 380, 380);
        resetFaceLoginState();
    }
}

//重置动画状态
function resetFaceLoginState() {
    $('#stateAnimPanel *').hide();
    $('#stateMsgPanel *').hide();
}

//开启摄像头
function openCamera() {
    if (!flag) {
        //获取摄像头对象
        canvas = document.getElementById("canvas");
        context = canvas.getContext("2d");
        //获取视频流
        video = document.getElementById("video");
        let videoObj = {
            "video": true
        }, errBack = function (error) {
            console.log("Video capture error: ", error.code);
        };
        //初始化摄像头参数
        if (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
            navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
            navigator.getUserMedia(videoObj, function (stream) {
                video.srcObject = stream;
                video.play();
                videoInterval = setInterval(function () {
                    context.scale(-1, 1);
                    context.drawImage(video, 110, 100, 380, 380, -200, 0, 200, 200);
                }, .5);
                startToRequest();
                flag = true;
            }, errBack);
        }
    }
}

//将当前图像传输到后台
function CatchCode() {
    //获取图像
    let img = getBase64();
    //Ajax将Base64字符串传输到后台处理
    $.ajax({
        async: false,
        type: "POST",
        url: "/user/faceLogin",
        data: {
            img: img
        },
        dataType: "JSON",
        success: function (data) {
            // console.log(data.result)
            if (data.error_code === 0 && data.result !== null && data.result.user_list[0].score > 93) {
                clearTimeout(loginTimeOut);
                clearInterval(faceLoginInterval);
                resetFaceLoginState();
                $('#faceLoginSuccess').show();
                $('#faceLoginSuccessMsg').show();
                setTimeout(function () {
                    $.ajax({
                        async: false,
                        type: "POST",
                        url: "/user/faceLoginSuccess",
                        data: {
                            originUrl: window.location.pathname,
                            userId: data.result.user_list[0].user_id
                        },
                        complete: function (data) {
                            window.location.reload();
                        }
                    });
                }, 1000)
            } else if (data.error_code === 223115) {
                $('#stateMsgPanel *').hide();
                $('#faceLightNotGood').show();
            } else if (data.error_code === 223119) {
                $('#stateMsgPanel *').hide();
                $('#faceLiveError').show();
            } else if (data.error_code === 223113) {
                $('#stateMsgPanel *').hide();
                $('#faceCover').show();
            } else if (data.error_code === 223114) {
                $('#stateMsgPanel *').hide();
                $('#faceLuzzy').show();
            } else if (data.error_code === 222202) {
                $('#stateMsgPanel *').hide();
                $('#faceNoDetect').show();
            } else {
                $('#stateMsgPanel *').hide();
                $('#faceLoadingMsg').show();
            }
        },
        error: function () {

        }
    });
};

// 获取画布base64字符串
function getBase64() {
    //获取当前图像并转换为Base64的字符串
    var imgSrc = canvas.toDataURL("image/png");
    //截取字符串
    return imgSrc.substring(22);
};

// 开始请求人脸登录
function startToRequest() {
    resetFaceLoginState();
    loginTimeOut = setTimeout(function () {
        clearInterval(faceLoginInterval);
        resetFaceLoginState();
        $('#faceLoginFail').show()
        $('#faceLoginFailMsg').show()
    }, 1000 * 20)
    faceLoginInterval = setInterval(function () {
        CatchCode()
    }, 1000);
    $('#faceLoading').show();
    $('#faceLoadingMsg').show();
}

//检测登录
function detectLogin() {
    let userAutoLogin = localStorage.getItem('autoLogin')
    if (userAutoLogin !== null && loginUser === undefined) {
        $.ajax({
            async: true,
            type: "POST",
            url: "/user/autoLogin",
            data: JSON.parse(userAutoLogin),
            success: function (result) {
                if (result)
                    window.location.reload();
            }
        });
    }
    let $loginDiv = $('#userDiv');
    $loginDiv.empty();
    if (loginUser !== undefined && loginUser !== null) {
        $.ajax({
            async: false,
            type: "POST",
            url: "/user/getUserById",
            data: {userId: loginUser.userId},
            success: function (result) {
                if (result !== undefined) {
                    let content = '<nav class="nav w-100">' +
                        '<ul class="w-100 nav justify-content-end">' +
                        '<li class="rounded-top ">' +
                        '<div class="d-flex p-2">' +
                        '<a class="p-0 mr-3 align-self-end text-white">' + result.userName + '</a>';
                    if (result.userFace !== null && result.userFace !== undefined && result.userFace.trim() !== '') {
                        content += '<img src="' + window.location.protocol + '//' + window.location.host + '/fileDownload/getUserFace?faceName=' + result.userFace + '" class="layui-circle" height="47" width="47">';

                    } else {
                        content += '<img src="' + window.location.protocol + '//' + window.location.host + '/fileDownload/getUserFace?faceName=defaultUser.jpg" class="layui-circle" height="47" width="47">';

                    }
                    content += '</div>' +
                        '<ul class="inner-dropdown rounded pl-2 ml-auto pr-2" style="z-index: 1;width: 200px;margin-left:110px;">' +
                        '<li>' +
                        '<a href="' + window.location.protocol + '//' + window.location.host + '/front/userGallery.jsp">个人中心</a>' +
                        '</li>' +
                        '<li>' +
                        '<a href="javascript:void(0);" onclick="logout()">退出</a>' +
                        '</li>' +
                        '</ul>' +
                        '</li>' +
                        '</ul>' +
                        '</nav>';
                    $loginDiv.append(content);
                } else {
                    let content = '<div class="d-flex w-100 p-2">' +
                        '<a href="javascript:void(0)" class=" align-self-end ml-auto text-white" style="color: white" onclick="doFastLogin()">未登录</a>' +
                        '<a href="javascript:void(0)" class="align-self-end" onclick="doFastLogin()">' +
                        '<span class="fa ml-3 fa-user-circle-o text-light"></span>' +
                        ' </a>' +
                        ' </div>';
                    $loginDiv.append(content);
                }
            }
        });
    } else {
        let content = '<div class="d-flex w-100 p-2">' +
            '<a href="javascript:void(0)" class=" align-self-end ml-auto text-white" style="color: white" onclick="doFastLogin()">未登录</a>' +
            '<a href="javascript:void(0)" class="align-self-end" onclick="doFastLogin()">' +
            '<span class="fa ml-3 fa-user-circle-o text-light"></span>' +
            ' </a>' +
            ' </div>';
        $loginDiv.append(content);
    }
}

// 验证码登录
function validateCodeLogin(data) {
    $.ajax({
        async: true,
        type: "POST",
        url: "/user/validateCodeLogin",
        data: data,
        success: function (result) {
            loginSuccess(result, data);
        }, error: function () {
            layer.msg('出错了');
        }
    });
}

// 点击发送验证码
$(document).on('click', '#getValidateCode', function () {
    let trim = $('#phoneNumberLogin').val().trim();
    if (trim === '') {
        layer.msg("请先填写手机号码");
    } else {
        $.ajax({
            async: false,
            type: "get",
            url: "/user/getValidateCode",
            data: {phoneNumber: trim},
            success: function (result) {
                if (result) {
                    layer.msg("获取验证码成功");
                    let $getValidateCode = $('#getValidateCode');
                    $getValidateCode.attr('disabled', true);
                    let count = 60;
                    let validateCodeInterval = setInterval(function () {
                        $getValidateCode.text(count + 'S 后重新获取');
                        count--;
                    }, 1000);
                    setTimeout(function () {
                        $getValidateCode;
                        clearInterval(validateCodeInterval);
                        $getValidateCode.text("发送验证码");
                        $getValidateCode.attr('disabled', false);
                    }, (count + 2) * 1000);

                } else {
                    layer.msg("获取验证码失败");
                }
            }
        });
    }
})


//进行登录操作
function doFastLogin() {
    // 开启弹出框
    layer.open({
        // 类型
        type: 1,
        // 标题
        title: ['快速登录', 'font-size:18px;'], //不显示标题栏
        // 是否显示 x 关闭按钮
        closeBtn: 1,
        // 设置弹出框大小
        area: ['600px', '450px'],
        // 背景隐形程度 1全黑 0没有阴影
        shade: 0.4,
        //设定一个id，防止重复弹出
        id: 'LAY_LayUiPro',
        // 不可移动
        move: false,
        // 不可调整大小
        resize: false,
        // 自定义内容
        content:
            '<div class="layui-tab layui-tab-brief" lay-filter="loginTab">' +
            '<ul class="layui-tab-title d-flex justify-content-center">' +
            // 标签1
            '<li class="layui-this">快速登录</li>' +
            // 标签2
            '<li>密码登录</li>' +
            '<li>人脸登录</li>' +
            '</ul>' +
            //标签内容容器
            '<div class="layui-tab-content" >' +
            // 标签内容1
            '<div class="layui-tab-item layui-show pr-4 pl-4">' +
            '<div class="text-center p-3 text-black-50">登录后即可快速下单与查件</div>' +
            '<form class="layui-form layui-form-pane" lay-filter="fastLoginForm">' +
            '<div class="layui-form-item layui-row">' +
            '<div class="layui-col-lg4">' +
            '<select name="countryCode" id="countryCode">' +
            '<option value="+86">中国内地 +86</option>' +
            '<option value="+852">中国香港 +852</option>' +
            '<option value="+886">中国台湾 +886</option>' +
            '<option value="+853">中国澳门 +853</option>' +
            '</select>' +
            '</div>' +
            '<div class="layui-col-lg8">' +
            '<input type="text" id="phoneNumberLogin" name="phoneNumberLogin" placeholder="填写手机号码" autocomplete="off" class="layui-input" lay-verify="required|phone">' +
            '</div>' +
            '</div>' +
            '<div class="layui-form-item layui-row layui-col-space15">' +
            '<div class="layui-col-lg8">' +
            '<input type="text" id="validateCode" name="validateCode" placeholder="填写验证码" autocomplete="off" class="layui-input" lay-verify="required">' +
            '</div>' +
            '<div class="layui-col-lg4">' +
            '<button type="button" id="getValidateCode" class="layui-btn layui-btn-radius w-100 layui-btn-normal" style="outline:none;">获取验证码</button>' +
            '</div>' +
            '</div>' +
            '<div class="layui-form-item text-center">' +
            '<input type="checkbox" name="autoLogin" title="自动登录" lay-skin="primary" checked>' +
            '</div>' +
            '<div class="text-center font-weight-lighter mb-2" style="font-size: 12px;color: #491217">' +
            '<cite title="未注册用户登录默认注册顺丰会员">未注册用户登录默认注册码上会员</cite>' +
            '</div>' +
            '<div class="layui-form-item text-center">' +
            '<button lay-submit lay-filter="fastLoginFormSubmit" id="fastLoginFormSubmit" class="layui-btn layui-btn-radius layui-btn-normal w-50" style="outline:none;">快速登录</button>' +
            '</div>' +
            '</form>' +
            '<div>' +
            '<div class="d-flex justify-content-end">' +
            '<a href="' + window.location.protocol + '//' + window.location.host + '/front/register.jsp" style="font-size: 12px;">既然你诚心想加入，那就去注册完整账号吧！</a>' +
            '</div>' +
            '</div>' +
            '</div>' +
            // 标签内容2
            '<div class="layui-tab-item pr-4 pl-4">' +
            '<div class="text-center p-3 text-black-50">登录后即可快速下单与查件</div>' +
            '<form class="layui-form layui-form-pane" lay-filter="pswLoginForm">' +
            '<div class="layui-form-item layui-row">' +
            '<label class="layui-form-label layui-bg-blue ml-4 text-white" for="phoneNumberForPsw">手机号</label>' +
            '<div class="layui-col-lg8">' +
            '<input type="text" id="phoneNumberForPsw" name="phoneNumberForPsw" placeholder="填写手机号码" autocomplete="off" class="layui-input" lay-verify="required|phone">' +
            '</div>' +
            '</div>' +
            '<div class="layui-form-item layui-row">' +
            '<label class="layui-form-label ml-4 layui-bg-blue text-white" for="passWord">密码</label>' +
            '<div class="layui-col-lg8">' +
            '<input type="password" id="passWord" name="passWord" placeholder="填写密码" autocomplete="off" class="layui-input" lay-verify="required">' +
            '</div>' +
            '</div>' +
            '<div class="layui-form-item text-center">' +
            '<input type="checkbox" name="autoLogin" title="下次自动登录" lay-skin="primary" checked>' +
            '</div>' +
            '<div class="layui-form-item text-center">' +
            '<button type="button" lay-submit="" lay-filter="pswLoginFormSubmit" class="layui-btn layui-btn-radius layui-btn-normal w-50" style="outline:none;">登录</button>' +
            '</div>' +
            '</form>' +
            '<div>' +
            '<div class="d-flex justify-content-end">' +
            '<a href="' + window.location.protocol + '//' + window.location.host + '/front/register.jsp" style="font-size: 12px;">既然你诚心想加入，那就去注册完整账号吧！</a>' +
            '</div>' +
            '</div>' +
            '</div>' +
            // 标签内容3
            '<div class="layui-tab-item pr-4 pl-4">' +

            '<div class="d-flex p-2 justify-content-center">' +
            '<video id="video" class="layui-hide" autoplay></video>' +
            '<canvas id="canvas" class="layui-circle" width="200" height="200"></canvas>' +
            '</div>' +
            '<div id="stateAnimPanel" class="d-flex p-2 justify-content-center">' +
            '<span id="faceLoading" class="fa fa-spin layui-anim layui-anim-scaleSpring fa-3x text-black-50 fa-refresh" style="display: none"></span>' +
            '<span id="faceLoginSuccess" class="fa fa-smile-o layui-anim layui-anim-scaleSpring fa-3x text-success" style="display: none"></span>' +
            '<a id="faceLoginFail" href="javascript:void(0)" onclick="startToRequest()" class="fa fa-frown-o layui-anim layui-anim-scaleSpring fa-3x text-danger" style="display: none"></a>' +
            '</div>' +
            '<div id="stateMsgPanel"  class="d-flex p-1 justify-content-center">' +
            '<span id="faceLightNotGood" class="layui-anim layui-anim-scaleSpring font-weight-bold text-black-50" style="display: none">光线太暗</span>' +
            '<span id="faceLoadingMsg" class="layui-anim layui-anim-scaleSpring font-weight-bold text-black-50" style="display: none">请调整面部角度以提高登录成功率</span>' +
            '<span id="faceLiveError" class="layui-anim layui-anim-scaleSpring font-weight-bold text-black-50" style="display: none">未检测到人脸</span>' +
            '<span id="faceNoDetect" class="layui-anim layui-anim-scaleSpring font-weight-bold text-black-50" style="display: none">未检测到人脸</span>' +
            '<span id="faceLuzzy" class="layui-anim layui-anim-scaleSpring font-weight-bold text-black-50" style="display: none">请不要摇晃摄像头</span>' +
            '<span id="faceCover" class="layui-anim layui-anim-scaleSpring font-weight-bold text-black-50" style="display: none">请不要遮挡面部</span>' +
            '<span id="faceLoginSuccessMsg" class="layui-anim layui-anim-scaleSpring font-weight-bold text-success" style="display: none">登陆成功</span>' +
            '<a href="javascript:void(0)" id="faceLoginFailMsg" onclick="startToRequest()" class="layui-anim layui-anim-scaleSpring font-weight-bold text-danger" style="display: none">验证失败，请使用密码登录或点击重试</a>' +
            '</div>' +
            '</div>' +
            // 标签内容3
            '</div>' +
            // 标签内容容器
            '</div>',
        // 弹出成功时的回调函数
        success: function () {
            //如果loginForm为undefined，进行弹出框的表单初始化，否则重新渲染
            if (form === undefined) {
                // 弹出框的表单初始化
                layui.use('form', function () {
                    form = layui.form;
                    form.on('submit(fastLoginFormSubmit)', function (data) {
                        console.log(data.field); //当前容器的全部表单字段，名值对形式：{name: value}
                        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                    });
                });
            } else {
                element.render('tab', 'loginTab');
                form.render();
            }
        },
        cancel: function () {
            closeCamera();
        }
    });
}

